//
//  TCChartListViewController.m
//  EFBTerminalCharts
//
//  Created by xiu-imac on 13-10-30.
//  Copyright (c) 2013年 adcc. All rights reserved.
//

#import "TCChartListViewController.h"
#import "TCAirportModel.h"
#import "TCChartCell.h"
#import "TCFavorateCell.h"

@interface TCChartListViewController ()
{
	NSMutableArray *favorateArray;
}
@property (retain, nonatomic) IBOutlet UINavigationBar *navigationBar;
@property (retain, nonatomic) IBOutlet UITableView *chartsTableView;
@property (retain, nonatomic) IBOutlet UIButton *allButton;
@property (retain, nonatomic) IBOutlet UIButton *selectedButton;
@property (retain, nonatomic) NSMutableArray *subTypesArray;
@property (retain, nonatomic) NSDictionary *typeDictionary;
@end

@implementation TCChartListViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:@"EFBFavoriteNotification"];

    [_navigationBar release];
    [_subTypesArray release];
    [_typeDictionary release];
	[_chartsTableView release];
	[super dealloc];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
		NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
		[center addObserver:self selector:@selector(selectedTypeChanged:) name:@"selectedTypeChanged" object:nil];
		[center addObserver:self selector:@selector(favorateButtonTapped:) name:@"kFavorateButtonTapped" object:nil];

    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	
    self.typeDictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"REFERENCE CHARTS",@"REF", @"ARRIVALS",  @"STR", @"APPROACH CHARTS", @"APP", @"TAXI CHARTS", @"TXI", @"DEPARTURES", @"SID", @"RNP AR", @"AR", @"COMPANY CHARTS", @"CO",@"机场细则",@"细则",@"补充资料",@"黄页",nil];
    
    self.view.backgroundColor = [UIColor colorWithRed:222/255.0 green:222/255.0 blue:222/255.0 alpha:1.0];

    [_navigationBar setBarTintColor:[UIColor colorWithRed:59/255.0 green:70/255.0 blue:85/255.0 alpha:1.0]];
    _navigationBar.topItem.title = @"";
    _navigationBar.translucent = NO;

	_chartsTableView.delegate = self;
	_chartsTableView.dataSource = self;
    _chartsTableView.backgroundColor = [UIColor colorWithRed:222/255.0 green:222/255.0 blue:222/255.0 alpha:1.0];
    _chartsTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;

	[_allButton setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
	[_allButton setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
	[_selectedButton setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
	[_selectedButton setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
	[_allButton setSelected:YES];
    
//    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.view.frame byRoundingCorners:UIRectCornerTopLeft |UIRectCornerTopRight | UIRectCornerBottomLeft |UIRectCornerBottomRight  cornerRadii:CGSizeMake(4, 4)];
//    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
//    maskLayer.frame = self.view.frame;
//    maskLayer.path = maskPath.CGPath;
//    self.view.layer.mask = maskLayer;
    [self setExtraCellLineHidden:_chartsTableView];
}

- (void)setExtraCellLineHidden: (UITableView *)tableView{
    
    UIView *view =[ [UIView alloc]init];
    
    view.backgroundColor = [UIColor clearColor];
    
    [tableView setTableFooterView:view];
    
    [tableView setTableHeaderView:view];
    
    [view release];
    
}
#pragma mark tableview datasource method

-(void)getFavorateInfo
{
	[favorateArray release];
	favorateArray = [[NSMutableArray alloc] init];
	
	for (NSDictionary *dic in [TCAirportModel getSubTypes:@""])
	{
		for (NSDictionary *chartDic in [dic objectForKey:@"chartsArray"])
		{
            NSString * favorate = [[TCAirportModel getFavorateDic] objectForKey:[chartDic objectForKey:@"file_name"]];
			if (favorate != nil && [favorate isEqualToString:@"YES"])
			{
				NSMutableDictionary *subTypeDic = [[[NSMutableDictionary alloc] init]autorelease];
				[subTypeDic setValue:[dic objectForKey:@"subTypeName"] forKey:@"subTypeName"];
				NSMutableArray *chartsArray = [[[NSMutableArray alloc] init] autorelease];
				for (NSDictionary *chartDic in [dic objectForKey:@"chartsArray"])
				{
                    NSString * isFavorate_1 = [[TCAirportModel getFavorateDic] objectForKey:[chartDic objectForKey:@"file_name"]];
					if (isFavorate_1 != nil && [isFavorate_1 isEqualToString:@"YES"])
					{
						[chartsArray addObject:chartDic];
					}
				}
				[subTypeDic setValue:chartsArray forKey:@"chartsArray"];
				[favorateArray addObject:subTypeDic];
				break;
			}
		}
	}
	NSLog(@"favorateArray: \n%@",favorateArray);
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30.0f;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	int count = [[[_subTypesArray objectAtIndex:section] objectForKey:@"chartsArray"] count];

	return count;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [_subTypesArray count];
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
	UIView *sectionView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 30.0f)] autorelease];
	UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, sectionView.frame.size.width-10, sectionView.frame.size.height)];
	[titleLabel setTextAlignment:NSTextAlignmentLeft];
	
    [titleLabel setText:[[_subTypesArray objectAtIndex:section] objectForKey:@"subTypeName"]];
	
	[titleLabel setTextColor:[UIColor colorWithRed:0x06/255.0 green:0xb7/255.0 blue:0x94/255.0 alpha:1.0]];
	[titleLabel setBackgroundColor:[UIColor clearColor]];
	[sectionView setBackgroundColor:[UIColor colorWithRed:222/255.0 green:222/255.0 blue:222/255.0 alpha:1.0]];
	[sectionView addSubview:titleLabel];
    [titleLabel release];
	return sectionView;
}

-(NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return [[_subTypesArray objectAtIndex:section] objectForKey:@"subTypeName"];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *chartsIdentifier=@"chartsIdentifier";
    TCChartCell *cell=[[[TCChartCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:chartsIdentifier ] autorelease];
    
    if (cell==nil) {
        cell = [[[NSBundle mainBundle]loadNibNamed:@"TCChartCell" owner:self options:nil]objectAtIndex:0];
    }
    NSDictionary *chartDic = [[[[TCAirportModel getSubTypes:@""] objectAtIndex:indexPath.section] objectForKey:@"chartsArray"] objectAtIndex:indexPath.row];
    NSString *airPort = [TCAirportModel getAirportICAO];
    NSString *type = [TCAirportModel getType];
	NSArray *array = [[[TCAirportModel getFavorateDic] objectForKey:airPort] objectForKey:type];
    if ([array containsObject:chartDic]) {
        [cell.favorateButton setSelected:YES];
    }
    else
    {
        if (![type isEqualToString:@"CO"]) {
            [cell.favorateButton setSelected:NO];
        }
        else {
            for (NSDictionary *dic in array) {
                if ((dic[@"uuid"] != nil && [dic[@"uuid"] isEqualToString:chartDic[@"uuid"]])) {
                    [cell.favorateButton setSelected:YES];
                    [TCAirportModel setFavorateDic:dic value:nil];
                    [TCAirportModel setFavorateDic:chartDic value:@"YES"];
                    break;
                }
                [cell.favorateButton setSelected:NO];
            }
        }
    }
    [cell.nameLabel setText:[chartDic objectForKey:@"name"]];
    [cell.pageLabel setText:[chartDic objectForKey:@"page"]];
    if ([type isEqualToString:@"黄页"]) {
        [cell.nameLabel setTextColor:[UIColor yellowColor]];
        [cell.pageLabel setTextColor:[UIColor yellowColor]];
    }
    if ([[chartDic objectForKey:@"is_modified"] intValue] == 1) {
        [cell.nameLabel setTextColor:[UIColor redColor]];
        [cell.pageLabel setTextColor:[UIColor redColor]];
    }
    //cell选中
    NSString *key = [airPort stringByAppendingString:type];
	NSDictionary *dic = [[TCAirportModel getSelectedDic] objectForKey:key];
    if ([type isEqualToString:@"CO"]) {
        if (dic[@"uuid"] != nil && [dic[@"uuid"] isEqual:chartDic[@"uuid"]]) {
            [tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
        }
    }else{
        if ([dic isEqual:chartDic]) {
            [tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
        }
    }
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    [tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
	NSMutableDictionary *chartDic = [[[[TCAirportModel getSubTypes:@""] objectAtIndex:indexPath.section] objectForKey:@"chartsArray"] objectAtIndex:indexPath.row];
	
	[TCAirportModel setSelectedDic:chartDic];
	
	[[NSNotificationCenter defaultCenter] postNotificationName:@"openPDF" object:chartDic];
}

#pragma ---

#pragma mark notification method

-(void)selectedTypeChanged:(NSNotification*)notification
{
	NSString *type = notification.object;
     
    NSString *title = [self.typeDictionary objectForKey:type];
    _navigationBar.topItem.title = title;
    if (self.subTypesArray) {
        [self.subTypesArray removeAllObjects];
        self.subTypesArray = nil;
    }
	self.subTypesArray = [NSMutableArray arrayWithArray:[TCAirportModel getSubTypes:type]];
//	[self getFavorateInfo];
//	[self allButtonTapped:nil];
	[_chartsTableView reloadData];
}
#pragma ---
#pragma mark event method
//五角星点击方法
-(void)favorateButtonTapped:(NSNotification *)notification
{
	NSIndexPath *indexPath = [_chartsTableView indexPathForCell:notification.object];
	   
	NSMutableDictionary *chartDic = [[[[TCAirportModel getSubTypes:@""] objectAtIndex:indexPath.section] objectForKey:@"chartsArray"] objectAtIndex:indexPath.row];
    NSString *airPort = [TCAirportModel getAirportICAO];
    NSString *type = [TCAirportModel getType];
	NSArray *array = [[[TCAirportModel getFavorateDic] objectForKey:airPort] objectForKey:type];
    NSString *favorate = @"NO";
    if (![array containsObject:chartDic]) {
        [TCAirportModel setFavorateDic:chartDic value:@"YES"];
        favorate = @"YES";
    }
    else
    {
        [TCAirportModel setFavorateDic:chartDic value:nil];
    }
//	[self getFavorateInfo];
    NSDictionary *d = @{@"type" : [TCAirportModel getType], @"favorate" : favorate, @"airport" : airPort };
    [[NSNotificationCenter defaultCenter] postNotificationName:@"EFBFavoriteNotification" object:chartDic userInfo:d];
}

- (IBAction)allButtonTapped:(id)sender
{
    [_allButton setSelected:YES];
    [_selectedButton setSelected:NO];
    [_chartsTableView reloadData];
}

- (IBAction)selectedButtonTapped:(id)sender {
    
    [_allButton setSelected:NO];
    [_selectedButton setSelected:YES];
    [_chartsTableView reloadData];
}


#pragma ---

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

@end
